package com.hxht.cmp.adapter;

import com.hxht.cmp.common.Constants;
import com.hxht.cmp.common.enums.ResultCode;
import com.hxht.cmp.common.result.ResultResponse;
import org.apache.log4j.Logger;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * Created by Alice on 2016/7/25 0025
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    private final static Logger log = Logger.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        if (Constants.SYSTEM_LOCKED == 1 && !url.contains("flush")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(ResultResponse.returnStr(ResultCode.SYSTEM_LOCKED.getCode(), ResultCode.SYSTEM_LOCKED.getMessage(), null));
            return false;
        }
//        log.info("\t"+request.getRequestURL().toString()+"\t-->\t"+"\tsessionId :\t"+request.getSession().getId()+"\tstart");
        //打印参数
        Enumeration enu = request.getParameterNames();
        StringBuilder str = new StringBuilder();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            str.append("[").append(paraName).append(":").append(request.getParameter(paraName)).append("] ");
        }
        String[] filtration = new String[]{".js", ".png", ".html", ".jsp", "css", ".jpg", ".gif", ".ttf", ".mp4", "warn"};
        if (url.contains("warn")) {
            return super.preHandle(request, response, handler);
        }
        if (ObjectUtils.isEmpty(str)) {
            log.info("\t" + url);
        } else {
            log.info("\t" + url + "\t params-->\t" + str);
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (!ObjectUtils.isEmpty(ex)) {
            log.error(ex.getLocalizedMessage(), ex);
        }
//        log.info("\t"+request.getRequestURL().toString()+"\t-->\t"+"\tsessionId :\t"+request.getSession().getId()+"\tend");
        super.afterCompletion(request, response, handler, ex);
    }
}
